package cash.cmp.personal_financial_system.controller.ws;

import cash.cmp.personal_financial_system.model.SysMsg;
import cash.cmp.personal_financial_system.model.User;
import cash.cmp.personal_financial_system.service.impl.SysMsgServiceImpl;
import cash.cmp.personal_financial_system.service.impl.UserServiceImpl;
import cash.cmp.personal_financial_system.utils.SpringUtil;
import cash.cmp.personal_financial_system.utils.allEnum.SysMsgEnum;
import cash.cmp.personal_financial_system.utils.shrioUtil.PwdUtil;
import cn.hutool.core.text.StrFormatter;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * {@code @ServerEndpoint} 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 * 注意：ServerEndpoint不能直接注入bean，需要通过获取Spring容器间接获取bean * *
 */
@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocketServer {
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
     */
    private static final ConcurrentHashMap<Integer, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

//    @Autowired
//    private SysMsgServiceImpl sysMsgService;
    /**
     * 缓存的消息,因为会存在同时写消息-读消息，写消息-删除消息的情况，需要保证线程安全*
     */
//    private static ConcurrentHashMap<Integer, List<String>> cacheMessage = new ConcurrentHashMap<>();

    public Session getSession() {
        return session;
    }

    /**
     * 接收userId
     */
    private Integer userId;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")Integer userId) {

        SysMsgServiceImpl sysMsgService = SpringUtil.getBean(SysMsgServiceImpl.class);

        this.session = session;

        if (userId == null) {
            log.info("用户id为空");
            return;
        }
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            // 如果再次连接 ，丢掉上次连接 ,存储本次连接
            webSocketMap.remove(userId);
            //加入map中
            webSocketMap.put(userId, this);
        } else {
            //加入map中
            webSocketMap.put(userId, this);
            //在线数加1
            addOnlineCount();
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        //是否有暂存的消息，如果有则发送消息, 及发送该用户所有的mysql中的消息；

//        boolean contains = cacheMessage.containsKey(userId);
//        List<String> Strings = cacheMessage.get(userId);
        List<SysMsg> msgs = sysMsgService.findMsgById(userId);
        List<String> strings = new ArrayList<>();
        for (SysMsg msg : msgs) {
            JSONObject jsonObject = changeJSONObject(msg);
//            System.out.println("1msg、" + msg.toString());
//            System.out.println("1json、" + jsonObject.toJSONString());
            strings.add(jsonObject.toJSONString());
        }

        if ( strings.size() != 0 ) {
            //取出消息列表
//            List<String> list = strings;
            strings.forEach(message -> {
                sendMessage(userId, message);
            });
            log.info("用户" + userId + "缓存的消息发送成功");
            strings = null;
        }else{
            log.info("用户" + userId + "没有缓存的消息");
        }
//        System.out.println("缓存的消息cacheMessage" + cacheMessage);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(this.userId)) {
            log.info("userId = ", userId);
            webSocketMap.remove(userId);
            //从set中删除
            //判断在线人数是否为0，避免在线人数出现负数
            if (WebSocketServer.onlineCount > 0) {
                subOnlineCount();
            }
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        UserServiceImpl userService = SpringUtil.getBean(UserServiceImpl.class);
        SysMsgServiceImpl sysMsgService = SpringUtil.getBean(SysMsgServiceImpl.class);

        User sendUser = userService.findUserById(this.userId);
        User objectUser = userService.findUserByTel(message);

        if(objectUser == null) {
            JSONObject json = new JSONObject();
            json.put("code",  400 );
            json.put("msg",  "fail" );
            json.put("data",  "电话号码错误" );
            sendMessage(sendUser.getId(), json.toJSONString());
        }

        Date now = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd ss");
        String msg = StrFormatter.format(SysMsgEnum.BINDING_MSG.getValue(),sendUser.getName(), objectUser.getName());

        SysMsg sm = new SysMsg();
        sm.setSendTime(now);
        sm.setType(0);
        sm.setReadState(0);
        sm.setObjectId(objectUser.getId());
        sm.setSendId(sendUser.getId());
        sm.setMsg(msg);

        sm.setMsgId(objectUser.getId() + "-" +  df.format(sm.getSendTime()) + "-" + PwdUtil.genRandomPwd(8) );

        sysMsgService.insertMsg(sm);
        System.out.println( "1、" +  sm.toString());
        // 把sysMsg对象 转换为 jsonObject对象;
        JSONObject jsonObject = changeJSONObject(sm);

        sendMessage( sm.getObjectId(), jsonObject.toJSONString());

        log.info("用户消息: " + userId + ",报文: " + msg + " tel: " + message);
        session.getBasicRemote().sendText("消息已发送至用户：" + objectUser.getName() + "邮箱");
    }


    /**
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Integer objectId, String massage) {
        try {
            boolean contains = webSocketMap.containsKey(objectId);
            if (contains) {
                WebSocketServer webSocketServer = webSocketMap.get(objectId);
                if (webSocketServer == null) {
                    log.info("WebSocket server not found");
                    return;
                }
                webSocketServer.getSession().getBasicRemote().sendText(massage);
                log.info("WebSocket 消息发送成功");
            } else {
                log.info("WebSocket 用户不在线，暂存消息");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * {@code @description:} 实现服务器主动推送实体消息
     * @author scx
     */
    public void sendObjectMessage(Object message) {
        try {
            this.session.getBasicRemote().sendObject(message);
        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得此时的在线人数
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人数加1
     */
    public static synchronized void addOnlineCount() {
//        System.out.println("在线人数加1");
        WebSocketServer.onlineCount++;
    }

    /**
     * 在线人数减1
     */
    public static synchronized void subOnlineCount() {
//        System.out.println("在线人数减1");
        WebSocketServer.onlineCount--;
    }

    public static JSONObject changeJSONObject(SysMsg sm){

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd ss");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgId", sm.getMsgId() );
        jsonObject.put("sendId", sm.getSendId() );
        jsonObject.put("objectId", sm.getObjectId() );
        jsonObject.put("msg", sm.getMsg() );
        jsonObject.put("type", sm.getType() );
        jsonObject.put("readState", sm.getReadState() );
        jsonObject.put("sendTime", df.format(sm.getSendTime()) );

        return jsonObject;
    }

}

